<template>
  <div>
    <h1 style="text-align: center">补货申请</h1>
    <hr>
  </div>
  <el-form ref="refRestockTable" :model="restock" label-width="80px">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-form-item label="申请门店:">
          <el-text>{{restock.storeName}}</el-text>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="申请人:">
          <el-text>{{ restock.managerName }}</el-text>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="日期:">
          <el-text>{{restock.submitTime}}</el-text>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="单据编号:">
          <el-text>{{ restock.replenishId }}</el-text>
        </el-form-item>
      </el-col>
    </el-row>


    <el-table  :data="tableData" @selection-change="handleMainTableSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" label="操作" class="custom-first-column">
        <template #header>
          <el-icon><Setting /></el-icon>
        </template>
        <template #default="scope">
          <el-button type="text" icon="Edit" @click="edit"></el-button>
          <el-button v-if="type" type="text" icon="Minus" @click="handleDelete(scope.$index)"></el-button>
        </template>
      </el-table-column>
      <el-table-column prop="itemInformation.id" label="商品编号" align="center" />
      <el-table-column prop="itemInformation.categoryName" label="商品类别" align="center" />
      <el-table-column prop="itemInformation.productName" label="商品名称" align="center" />
      <el-table-column prop="itemInformation.manufacturer" show-overflow-tooltip label="生产地" align="center" />
      <el-table-column v-if="type" prop="quantity" label="商品数量" align="center" >
        <template #default="scope">
          <el-input-number  v-model="scope.row.quantity"  size="small" @change="handleChange(scope.row)"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column v-else prop="quantity" label="商品数量" align="center" />
      <el-table-column prop="itemInformation.price" label="销售单价(元)" align="center" />
      <el-table-column prop="description" label="备注" align="center" />
      <el-table-column v-if="!type" label="操作" align="center" class-name="small-padding fixed-width">
      </el-table-column>
    </el-table>

    <div v-if="type" style="text-align: center; margin-top: 20px;">
      <el-button type="text" icon="Plus" @click="addRow"></el-button>
    </div>

    <!-- 按钮区域 -->
    <el-row style="text-align: right; padding-top: 30px">
      <el-col>
        <el-button type="primary" @click="mainCancel">返回</el-button>
        <el-button v-if="restock.status !== '已审核'  " type="primary" @click="submitMainForm">提交审核</el-button>
        <el-button v-if="restock.status === null || '已保存' " type="primary" @click="save">保存</el-button>
      </el-col>
    </el-row>
  </el-form>

  <!-- 商品列表表格 -->
  <el-dialog title="选择商品" v-model="open" heght="1000px" width="1000px" append-to-body>
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="productName">
        <el-input
            v-model="queryParams.productName"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品类别" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择商品类别" clearable>
          <el-option v-for="item in categoryOptions" :key="item.id" :label="item.category" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="productList" ref="refProductTable" @selection-change="handleSelectionChange" >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编号" align="center" prop="id" />
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="商品类别" align="center" prop="categoryName" />
      <el-table-column label="商品属性" align="center" prop="attributeN" />
      <el-table-column label="供货商" align="center" prop="manufacturer" />
      <el-table-column label="销售价格" align="center" prop="'price'" :formatter="formatPrice" >
        <template #default="{ row }">
          {{ formatPrice(row, 'price') }}
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getProductList"
    />


    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>

import {getStockDetail,updateStockDetail,sendRestock,saveRestock} from "@/api/restock/restock.js";
import {listProduct,getProductCategory} from "@/api/product/product.js";
import {ElMessage} from "element-plus";


const route = useRoute();
const open = ref(false);
const tableData = ref([]);
const total = ref(0);
const showSearch = ref(true);
const restock = ref({});
const refProductTable = ref(null);
const productList = ref([]);
const multipleSelection = ref([])
const categoryOptions = ref([])
const { proxy } = getCurrentInstance();
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  productName: '',
  categoryId: null
})
const type = ref(false);// 声明 `type` 变量

function getType(storeId, restockId) {
  if (restockId !== undefined) {
    // 详情
    type.value = false;
  } else if (storeId !== undefined) {
    // 新增
    type.value = true;
  } else {
    // 如果两个参数都没有，`type` 保持为 `null`
    type.value = null;
  }
}

function getList(restockId, storeId) {
  if (type.value === false) {
    getStockDetail(restockId).then(response => {
      tableData.value = response.data.restockProducts;
      restock.value = response.data;
    });
  } else if (type.value === true) {
    updateStockDetail(storeId).then(response => {
      restock.value = response.data;
      console.log(restock.value)
    });
  }
}

// 多选框选中数据
function handleSelectionChange(selection) {
  multipleSelection.value = selection
}

// 格式化函数
function formatPrice(row, property) {
  return `${row[property]}元`;
}

// 取消按钮
function cancel() {
  open.value = false;
}

function handleDelete(index){
  // 删除指定索引的行
  tableData.value.splice(index, 1)
}


function handleChange(row) {
  row.quantity = row.quantity;
}


function getProductList() {
  console.log(queryParams.value)
  listProduct(queryParams.value).then(response =>{
    // console.log(response);
    productList.value = response.rows;
    total.value = response.total;
  });
  getProductCategory().then(response => {
    categoryOptions.value = response.data;
  });
}

/** 开启选择商品 */
function addRow(){
  open.value = true;
  getProductList();
}

function edit(){
  type.value = true;
}

function submitForm(){
 if(multipleSelection.value.length === 0){
   ElMessage.warning('请至少选择一个商品')
   return
 }
  const newItems = multipleSelection.value.map(item => ({
    itemInformation : {
      id: item.id,
      categoryName: item.categoryName,
      productName: item.productName,
      manufacturer: item.manufacturer,
      price: item.price
    },
    quantity: 1, // 默认数量为1，可以根据需求调整
    description: ''
  }))

  //不能添加相同的商品
  if (tableData.value.some(item => item.itemInformation.id === newItems[0].itemInformation.id)) {
    ElMessage.warning('商品已存在，请勿重复添加');
    return;
  }
  tableData.value.push(...newItems)
  open.value = false;
}

/** 主表提交审核 */
function submitMainForm(){
  proxy.$refs["refRestockTable"].validate(valid => {
    if (valid) {
      if (tableData.value === null || tableData.value.length === 0) {
        ElMessage.warning('请至少选择一个商品')
        return
      } else {
        restock.value.restockProducts = tableData.value;
        console.log(restock.value)
        sendRestock(restock.value).then(response => {
          //状态码：200 成功
          if (response.code === 200) {
            ElMessage.success("提交成功");
            proxy.$emit('ok');
            mainCancel();
          }else if (response.code === 500) {
            ElMessage.error(response.msg);
          }
        });
      }
    }
  });
}

function save(){
  proxy.$refs["refRestockTable"].validate(valid => {
    if (valid) {
      if (tableData.value === null || tableData.value.length === 0) {
        ElMessage.warning('请至少选择一个商品')
        return
      } else {
        restock.value.restockProducts = tableData.value;
        saveRestock(restock.value).then(response => {
          //状态码：200 成功
          if (response.code === 200) {
            ElMessage.success("提交成功");
            proxy.$emit('ok');
            mainCancel();
          }else if (response.code === 500) {
            ElMessage.error(response.msg);
          }
        });
      }
    }
  });
}


/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getProductList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.productName = ''
  queryParams.categoryId = null
  handleQuery();
}

/** 主表取消按钮操作 */
function mainCancel() {
  // const obj = { path: "/restock/restock/restock" };
  // proxy.$tab.closeOpenPage(obj);
  proxy.$router.push('/restock/restock');
}

const { storeId, restockId } = route.query;
getType(storeId, restockId);
getList(restockId, storeId);

</script>

<style scoped>

.el-input-number--small {
  width: 90px;
  line-height: 22px;
}

</style>